package com.xjtu.mybatisplus.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xjtu.mybatisplus.common.context.BaseContext;
import com.xjtu.mybatisplus.common.result.Result;
import com.xjtu.mybatisplus.common.utls.RedisUtil;
import com.xjtu.mybatisplus.model.dto.MailDTO;
import org.springframework.data.redis.core.ReactiveRedisOperations;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.xjtu.mybatisplus.common.JsonResponse;
import com.xjtu.mybatisplus.service.MailboxService;
import com.xjtu.mybatisplus.model.domain.Mailbox;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 *
 *  前端控制器
 *
 *
 * @author lsong
 * @since 2023-12-27
 * @version v1.0
 */
@RestController
@RequestMapping("/api/mailbox")
public class MailboxController {

    private final Logger logger = LoggerFactory.getLogger( MailboxController.class );

    @Autowired
    private MailboxService mailboxService;

    @Autowired
    private RedisUtil redisUtil;

    @PutMapping("/add")
    public JsonResponse add(@RequestBody String content){
        mailboxService.addMail(content);
        return JsonResponse.successMessage("信件添加成功");
    }

    @PutMapping("/reply")
    public JsonResponse replyMail(@RequestBody MailDTO mailDTO){
        redisUtil.del("publicMailbox");
        mailboxService.replyMail(mailDTO);
        return JsonResponse.successMessage("信件回复成功");
    }

    @PutMapping("/public")
    public JsonResponse setPublic(@RequestBody MailDTO mailDTO){
        redisUtil.del("publicMailbox");
        mailboxService.setPublic(mailDTO);
        return JsonResponse.successMessage("公开状态设置成功");
    }

    @DeleteMapping("/delete/{id}")
    public JsonResponse deleteById(@PathVariable Long id) {
        redisUtil.del("publicMailbox");
        mailboxService.removeById(id);
        return JsonResponse.successMessage("删除信件成功");
    }

    @GetMapping("/list")
    public JsonResponse listByNum(@RequestParam(value = "num", required = false) Integer num,
                                  @RequestParam("pageNo") Integer pageNo,
                                  @RequestParam("pageSize") Long pageSize) {

        // 检查num是否为2（公共邮箱），并尝试从缓存中检索数据
        if (num != null && num == 2) {
            String cacheKey = "publicMailbox";
            Page<Mailbox> page = (Page<Mailbox>) redisUtil.get("publicMailbox");
            if (page!=null&&page.getSize()==pageSize&&page.getCurrent()==pageNo) {
                Map<String, Object> data = new HashMap<>();
                data.put("total", page.getTotal());
                data.put("rows", page.getRecords());
                return JsonResponse.success(data, "从缓存成功查询数据");
            }
        }

        // 如果不在缓存中或num不是2，则使用原始逻辑继续
        Page<Mailbox> page = new Page<>(pageNo, pageSize);
        QueryWrapper<Mailbox> queryWrapper = new QueryWrapper<>();
        if (num != 3) {
            if (num != 2) {
                queryWrapper.eq("status", num);
            } else {
                queryWrapper.eq("is_public", 1);
            }
        }
//num为0代表查询未回复的信件,为1查询已回复的信件,为2查询已公开的信件,为3则查询全部信件
        queryWrapper.orderByDesc("create_time");
        mailboxService.page(page, queryWrapper);


        // 如果不是缓存命中，执行原始逻辑
        Map<String, Object> data = new HashMap<>();
        data.put("total", page.getTotal());
        data.put("rows", page.getRecords());
        // 更新缓存 for public mailboxes
        if (num != null && num == 2) {
            redisUtil.set("publicMailbox", page);
        }
        return JsonResponse.success(data, "成功查询数据");
    }

    @GetMapping("/userList")
    public JsonResponse listByUserId(@RequestParam("pageNo") Integer pageNo,
                                  @RequestParam("pageSize") Long pageSize,
                                     @RequestParam("userId") Long userId){
        Page<Mailbox> page = new Page<>(pageNo, pageSize);
        Map<String, Object> data = new HashMap<>();
        QueryWrapper<Mailbox> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        mailboxService.page(page, queryWrapper);
        data.put("total", page.getTotal());
        data.put("rows", page.getRecords());
        return JsonResponse.success(data,"查询数据成功");
    }
}

